package com.atguigu.study.base.SaleTick;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 快点干早点散
 * @Create 2025/4/22 20:34
 * Description:
 */
public class SyncVSLockDemo {
    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "\t");
        //暂停四秒
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private final Lock lock = new ReentrantLock();

    public void m2() {
        if (lock.tryLock()) {
            try {

                System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
                //暂停几秒线程
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "枪锁失败");
        }
    }

    public void m3() {
        try {
            if (lock.tryLock(2L,TimeUnit.SECONDS)) {
                try {

                    System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
                    //暂停几秒线程
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "超过2秒枪锁失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    public static void main(String[] args) {
        {
            SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();
            new Thread(() -> {
                syncVSLockDemo.m2();
            }, "t1").start();
            new Thread(() -> {
                syncVSLockDemo.m2();
            }, "t2").start();
        }
    }
}